package com.my.xq.service.impl;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.my.xq.domain.CourtQueryParam;
import com.my.xq.domain.entity.Court;
import com.my.xq.domain.entity.Plan_Court;
import com.my.xq.domain.entity.RenWu;
import com.my.xq.domain.entity.RenWuDefine;
import com.my.xq.repository.CourtRepository;
import com.my.xq.repository.DoorplateRepository;
import com.my.xq.repository.RenWuCreateRepository;
import com.my.xq.repository.RenWuRepository;
import com.sskj.core.annotation.ControllerLogExeTime;
import com.sskj.core.exception.MException;
import com.sskj.sys.domain.entity.MediaEntity;
import com.sskj.sys.repository.MediaRepository;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/xq")
public class CourtServiceImpl {
	@Autowired
	CourtRepository courtRepository;

	@Autowired
	DoorplateRepository doorplateRepository;

	@Autowired
	RenWuRepository rwRepository;

	@Autowired
	RenWuCreateRepository rwCreateRepository;

	@Autowired
	MediaRepository mediaRepository;
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/addxqInfo", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "添加小区信息")
	public void addxqInfo(Court c) {
		boolean add=false;
		if(null==c.getId()||"".equals(c.getId())) {	
			add=true;
		}
		Court court=courtRepository.save(c);
		if(add) {	//新增小区的时候去添加任务
			addRenWu(court.getId());
		}
		if (!c.getFiles().isEmpty()) {
			mediaRepository.updateMedia(court.getId(), this.toList(c.getFiles(), ","));
		}

		mediaRepository.delMedia(c.getId(),
				this.toList(c.getFiles().isEmpty() ? "XXXXX" : c.getFiles(), ","));
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/update/wyCount", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "跟新委员数量")
	public boolean updateWyCount(String courtId, int wyCount) {
		try {
			Court c = courtRepository.get(courtId);
			if (c != null) {
				c.setWyCount(wyCount);
				courtRepository.save(c);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
	
	public void addRenWu(String courtId) {
		

		for(RenWuDefine d : RenWuDefine.toupiaos())
		{
			List<RenWu> r = rwRepository.findRenWuLsByCourt(courtId,d.name());
			if(null==r || r.isEmpty())
			{
				RenWu rw =  new RenWu(d,courtId);
				rwRepository.save(rw);	
			}			
		}

		
	
		
	}		
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/findAllPage", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "查询小区信息并分页")
	@ApiOperation(value = "查询小区信息", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "姓名", paramType = "form", dataType = "string"),
		@ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
		@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<Court> findAllPage(@ApiIgnore CourtQueryParam cqp,@ApiIgnore Pageable pageable,HttpServletRequest request) {
		Page<Court> page = courtRepository.findPage(cqp,pageable);
		return page;
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询所有小区信息", log = false)
	@RequestMapping("/findAll")
	public List<Court> findAll() {
		List<Court> list=courtRepository.findAll();
		return list;
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询一条小区记录", log = false)
	@RequestMapping("/findOne")
	public Court findOne(String id,HttpServletRequest request) {
		Court court = courtRepository.get(id);
		//getUrlAndBfb(court, request);	//获取图片url,但不能获取图片尺寸以及相关的详细信息
		return court;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "删除小区信息", log = false)
	@RequestMapping("/delxq")
	public void delxq(String id) {
		courtRepository.delete(id);
		mediaRepository.delMedia(id,this.toList("XXXXX", ","));
		// 删除小区的同时删除小区所属的门牌
		doorplateRepository.delByCourtId(id);
		// 删除业委会选举任务
		rwRepository.delByCourtId(id);
		rwCreateRepository.delByCourtId(id);
		//List<String> ids = doorplateRepository.findIdByCourtId(id);
		//doorplateRepository.delete(ids);
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "根据方案id查询未被此方案选择的小区", log = false)
	@RequestMapping("/findNotSelectedCourt")
	public List<Court> findNotSelectedCourt(Plan_Court pc) {
		return courtRepository.findNotSelectedCourt(pc.getCourtName(), pc.getPlanid());
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "根据方案id查询已被此方案选择的小区", log = false)
	@RequestMapping("/findSelectedCourt")
	public List<Court> findSelectedCourt(Plan_Court pc) {
		return courtRepository.findSelectedCourt(pc.getPlanid());
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询图片", log = false)
	@RequestMapping(value = "/img/getFiles", method = { RequestMethod.GET })
	public List<MediaEntity> queryFiles(String aId) throws MException {
		List<MediaEntity> results = mediaRepository.queryPic(aId);
		return results;
	}
	
	public List<String> toList(String value, String separator) {
		List<String> result = new ArrayList<String>();
		if (!this.isEmpty(value)) {
			String[] as = value.split(separator);
			for (int i = 0; i < as.length; i++) {
				result.add(as[i]);
			}
		}
		return result;
	}
	
    public boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
    
	public void getUrlAndBfb(Court c, HttpServletRequest request) {
		List<MediaEntity> mes = mediaRepository.queryPic(c.getId());
		for (MediaEntity me : mes) {
			c.getUrlList().add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ "/" + me.getHttpurl());
		}
	}
}
